package com.dycong.common.IO.socket.BIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * Created by dycong on 2017/3/23.
 */
public class BIOClient {
    Logger log = LoggerFactory.getLogger(BIOClient.class);

    private static String HOST = "localhost";
    private static int PORT = 12122;
    //todo 此处没必要设为static，可以创建同一个romote addr的Socket
    private Socket socket = null;

    public BIOClient() {
    }

    public BIOClient(String host, int port) {
        HOST = host;
        PORT = port;
    }

    public void start() {
        start(HOST, PORT);
    }

    private void start(String host, int port) {
        PrintWriter out=null;
        BufferedReader in=null;
        try {
            socket = new Socket(host, port);
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out.write(Thread.currentThread().getName() + System.currentTimeMillis()+"asdasdasdasdasdasdsdsa \r\n");
            out.flush();
            //TODO  调用Socket的shutdownOutput()方法
            socket.shutdownOutput();
            StringBuffer result = new StringBuffer("");
            String tmp = null;
            // TODO 因为Server端Socket在write()数据之后就没有代码执行了，接下来就是执行finally代码块里的close(或者自动关闭：带资源的try块)方法了，所以不会引起客户端的读阻塞
            while ((tmp = in.readLine()) != null) {
                result.append(tmp);
                tmp=null;
            }
            log.info("the server response:" + result.toString());
            System.out.println("the server response:" + result.toString());
        } catch (IOException e) {
            log.info("client socket error:" + e);
            System.out.println("client socket error:" + e);
        }finally {
            try {
                // TODO: 一定记得关闭资源
                socket.close();
                in.close();
                out.close();
            }catch (IOException e){
                log.info("client socket close error: "+e);
            }

            if (socket!=null)
            socket=null;
        }
    }
}
